#include <algorithm>
using namespace std;

class Solution {
private:
    int max_len = 0;

    int dfs(TreeNode* root) {
        if (!root) return 0;

        int left = dfs(root->left);
        int right = dfs(root->right);

        int left_contribution = (root->left && root->left->val == root->val) ? left + 1 : 0;
        int right_contribution = (root->right && root->right->val == root->val) ? right + 1 : 0;

        max_len = max(max_len, left_contribution + right_contribution);
        return max(left_contribution, right_contribution);
    }

public:
    int longestUnivaluePath(TreeNode* root) {
        dfs(root);
        return max_len;
    }
};